package com.hyd.tweet.twitter;

import com.hyd.tweet.user.User;
import com.hyd.tweet.user.UserManager;
import com.hyd.tweet.util.Cache;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

/**
 * (description)
 *
 * @author yiding.he
 */
public class TwitterUtils {

    private static final TwitterFactory FACTORY;

    static {
        FACTORY = new TwitterFactory();
    }

    public static Twitter getTwitter(String token, String tokenSecret) {
        String cacheKey = token + " | " + tokenSecret;
        
        if (!Cache.containsKey(cacheKey)) {
            Twitter twitter = createTwitter(token, tokenSecret);
            Cache.put(cacheKey, twitter);
            return twitter;
            
        } else {
            return Cache.get(cacheKey);
        }
    }

    private static Twitter createTwitter(String token, String tokenSecret) {
        Twitter twitter = FACTORY.getInstance();
        twitter.setOAuthAccessToken(new AccessToken(token, tokenSecret));
        return twitter;
    }

    public static Twitter getTwitter(String account) {
        return getTwitter(UserManager.getUser(account));
    }

    public static Twitter getTwitter(User user) {
        if (user != null) {
            return getTwitter(user.getToken(), user.getTokenSecret());
        } else {
            return null;
        }
    }

    public static Twitter createAnonymousTwitter() {
        return FACTORY.getInstance();
    }
}
